package com.example.denglanya;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.appcompat.app.AppCompatActivity;

import com.example.denglanya.AAChartCoreLib.AAChartCreator.AAChartModel;
import com.example.denglanya.AAChartCoreLib.AAChartCreator.AAChartView;
import com.example.denglanya.AAChartCoreLib.AAChartCreator.AASeriesElement;
import com.example.denglanya.AAChartCoreLib.AAChartEnum.AAChartType;
import com.example.denglanya.AAChartCoreLib.AAOptionsModel.AAOptions;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.ConnectCallback;
import cn.wandersnail.bluetooth.Connection;
import cn.wandersnail.bluetooth.EventObserver;
import cn.wandersnail.commons.observer.Observe;
import cn.wandersnail.commons.poster.RunOn;
import cn.wandersnail.commons.poster.Tag;
import cn.wandersnail.commons.poster.ThreadMode;

public class MainActivity extends AppCompatActivity implements EventObserver {
    private String blName = "JDY-31-SPP";
    private final String TAG = "6666";
    private String uuid = "00001101-0000-1000-8000-00805F9B34FB";
    private Boolean isLogin = false;


    private TextView textView;
    private Button btSend;
    private EditText editText;
    private AAChartView aaChartView;
    private List<Double> list = new ArrayList<>();


    private Connection connection;
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothDevice mBluetoothDevice;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //实例化并初始化
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "当前设备不支持蓝牙,请更换手机，即将退出", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            }
        }
        // Android 6.0动态请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.ACCESS_COARSE_LOCATION};
            for (String str : permissions) {
                if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(permissions, 111);
                    break;
                }
            }
        }
        initView();
        setPairingDevice();
        picture();
        sendMsg();


    }


    /*初始化蓝牙连接*/
    private void initView() {

        textView = (TextView) findViewById(R.id.tv);
        btSend = (Button) findViewById(R.id.bt_send);
        editText = (EditText) findViewById(R.id.et);
        aaChartView = findViewById(R.id.AAChartView);

        BTManager.getInstance().initialize(getApplication());
        BTManager.isDebugMode = false;//开启日志打印
        BTManager.getInstance().registerObserver(this);
    }

    @SuppressLint("MissingPermission")
    private Boolean setPairingDevice() {
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        if (devices.size() > 0) { //存在已配对过的设备
            //利用for循环读取每一个设备的信息
            for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext(); ) {
                BluetoothDevice btd = it.next();
                if ("JDY-31-SPP".equals(btd.getName().toString())) {
                    mBluetoothDevice = btd;
                    Log.d(TAG, mBluetoothAdapter.getAddress().toString());
                    return true;
                }
            }
            Toast.makeText(this, "您当前还没匹配蓝牙，请打开设备,到手机蓝牙页面连接蓝牙JDY-31-SPP,pin为0000,并重启该软件", Toast.LENGTH_LONG).show();
            return false;
        } else {
            Toast.makeText(this, "您当前还没匹配蓝牙，请打开设备,到手机蓝牙页面连接蓝牙JDY-31-SPP,pin为0000,并重启该软件", Toast.LENGTH_LONG).show();
            return false;
        }
    }


    /**
     * 使用{@link Observe}确定要接收消息，{@link RunOn}指定在主线程执行方法，设置{@link Tag}防混淆后找不到方法
     */
    @Tag("onConnectionStateChanged")
    @Observe
    @RunOn(ThreadMode.MAIN)
    @Override
    public void onConnectionStateChanged(@NonNull BluetoothDevice device, int state) {
        switch (state) {
            case Connection.STATE_CONNECTING:
                break;
            case Connection.STATE_PAIRING:
                break;
            case Connection.STATE_PAIRED:
                break;
            case Connection.STATE_CONNECTED:
                break;
            case Connection.STATE_DISCONNECTED:
                break;
            case Connection.STATE_RELEASED:
                break;
        }
    }

    /**
     * 如果{@link BTManager.Builder#setObserveAnnotationRequired(boolean)}设置为false时，无论加不加{@link Observe}注解都会收到消息。
     * 设置为true时，必须加{@link Observe}才会收到消息。
     * 默认为false，方法默认执行线程在{@link BTManager.Builder#setMethodDefaultThreadMode(ThreadMode)}指定
     */
    @Observe
    @Override
    public void onRead(@NonNull BluetoothDevice device, @NonNull byte[] value) {
        String rec = new String(value);
        //去除空格
        rec = rec.replaceAll("[\t\n\r]", "");
//        Log.d("6666", "收到数据int：" + Integer.parseInt(rec));
        Log.d("6666", "收到数据dou：" + Double.parseDouble(rec));
        textView.setText(rec);
//        Log.d("6666", "收到数据1：" + rec);
        list.add(Double.parseDouble(rec));
//        Log.d("6666", "收到数据2：" + rec);
//        Log.d("6666", "收到数据3：" + rec);
        repeatUpdateChartData(list.toArray());

    }

    @Override
    public void onWrite(@NonNull BluetoothDevice device, @NonNull String tag, @NonNull byte[] value, boolean result) {
        Log.d(TAG, "写入结果：" + result);

    }

    /**
     * 发送信息
     */
    private void sendMsg() {
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    String msg = editText.getText().toString();
                    String res = msg + "\n";
                    connection.write(TAG, res.getBytes(StandardCharsets.UTF_8), null);
                } else {
                    Toast.makeText(MainActivity.this, "未连接蓝牙", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    /**
     * 连接蓝牙
     */
    private void openBl(BluetoothDevice bluetoothDevice, String uuid) {

        connection = BTManager.getInstance().createConnection(bluetoothDevice);
        connection.connect(UUID.fromString(uuid), new ConnectCallback() {
            @Override
            public void onSuccess() {

                Log.d(TAG, "连接成功");
                isLogin = true;
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                Log.d(TAG, errMsg);
                isLogin = false;
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "连接失败:" + errMsg, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });


    }

    /**
     * 关闭蓝牙
     */
    private void closeBl(BluetoothDevice bluetoothDevice) {
        BTManager.getInstance().disconnectConnection(bluetoothDevice);
        Log.d(TAG, "关闭成功");
        isLogin = false;
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(new AASeriesElement[]{
                        new AASeriesElement()
                                .data(null),
                });
                list.clear();
                textView.setText("00.00");
                Toast.makeText(MainActivity.this, "关闭成功", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 绘制图形
     */
    private void picture() {
        AAChartModel aaChartModel = new AAChartModel()
                .animationType("EaseOutCubic")
                .chartType(AAChartType.Spline)
                .title("心率图")
                .xAxisTickInterval(10)
//                .markerSymbolStyle("")
//                .subtitle("Virtual Data")
                .backgroundColor("#e4e4ec")
//                .categories(new String[]{"Java","Swift","Python","Ruby", "PHP","Go","C","C#","C++"})
                .dataLabelsEnabled(false)
                .yAxisGridLineWidth(0f)
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("心率")
//                                .step(true)
//                                .data(new Object[]{18, 18, 18, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6}),

                });

        AAOptions aaOptions = aaChartModel.aa_toAAOptions();

        aaChartView.aa_drawChartWithChartOptions(aaOptions);

    }

    private void repeatUpdateChartData(Object[] data) {
        final Handler mHandler = new Handler();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(new AASeriesElement[]{
                        new AASeriesElement()
                                .data(data),

                });
            }
        };
        mHandler.post(r);//延时2000毫秒
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.open:
                openBl(mBluetoothDevice, uuid);
                break;
            case R.id.close:
                closeBl(mBluetoothDevice);
                break;
        }
        return true;
    }
}